/*
 * @Description:
 * @Author: ye_xf
 * @Date: 2022-08-01 15:07:45
 * @LastEditTime: 2022-08-05 14:51:01
 * @LastEditors: ye_xf
 * @Reference:
 */

import Vue from 'vue'
import store from '@/store'
import * as types from '@/store/Getter/getterTypes.js'
import { getUTCStr, matchTimeToUTC } from '../timezone'
import { PERMISSION_QUEUE, PORTAL, DATA_SAFE } from '@/store/State/stateTypes.js'
import { REMOVE_PERMISSION_QUEUE } from '@/store/Mutation/mutationTypes.js'
import { verifyRequest, verifyResponse } from './verify'
import { SM4Encrypt } from '@/utils/encryption/sm4'
import { PORTAL_ID } from "@/config/app/develop"

const getFawkesBiz = (config) => {
  let FawkesBiz = {}

  // 通过请求头传递时区
  if (store.getters[types.TIMEZONE]) {
    let UTC = getUTCStr(store.getters[types.TIMEZONE])
    FawkesBiz.timeZone = UTC
    FawkesBiz.timeFormat = 'yyyy-MM-dd HH:mm:ss'
    // 将数据中HH:mm这类时区转为UTC存储
    if (UTC !== 'UTC+08:00') {
      if (config.data && !(config.data instanceof FormData)) {
        config.data = JSON.parse(matchTimeToUTC(JSON.stringify(config.data)))
      }
      if (config.params) {
        config.params = JSON.parse(matchTimeToUTC(JSON.stringify(config.params)))
      }
    }
  }

  if (store.getters[types.MULTI_PORTAL] && store.state[PORTAL]) {
    FawkesBiz.portalId = store.state[PORTAL].id ? store.state[PORTAL].id : PORTAL_ID
  } else {
    FawkesBiz.portalId = PORTAL_ID
  }

  //子应用适配
  let currentStore = Vue.prototype.$InQianKun ? Vue.prototype.$fksMainStore : store
  //请求头定位权限
  if (currentStore) {
    const arr = Array.from(currentStore.state[PERMISSION_QUEUE])
    const currentButton = arr.find((permission) => {
      return permission.url === config.url
    })

    if (currentButton) {
      currentStore.commit(REMOVE_PERMISSION_QUEUE, currentButton)
      FawkesBiz.buttonId = currentButton.id
    }
  }
  const len = config.url.indexOf('?')
  const subUrl = (len > -1 ? config.url.substring(config.url.indexOf('/', 1), len) : config.url.substring(config.url.indexOf('/', 1))) || config.url
  const requestEncrypt = verifyRequest(config) && store.state[DATA_SAFE].requestEncrypt
  const responseEncrypt = verifyResponse({ config }) && store.state[DATA_SAFE].responseEncrypt

  const apiCrypto = {
    requestEncrypt: {
      encrypt: requestEncrypt,
      ignoreUrl: requestEncrypt ? '' : subUrl
    },
    responseEncrypt: {
      encrypt: responseEncrypt,
      ignoreUrl: responseEncrypt ? '' : subUrl
    }
  }

  FawkesBiz = { ...FawkesBiz, apiCrypto }

  return SM4Encrypt(JSON.stringify(FawkesBiz))
}

export default getFawkesBiz